from flask import Blueprint, render_template, jsonify, redirect, url_for, request, session, g
from exts import mail, db
from flask_mail import Message
import string
import random
from models import EmailCaptchaModel, UserModel, SpeciesModel, SiteModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint("auth", __name__, url_prefix="/")

@bp.route("/", methods=['GET','POST'])
def login():
    if request.method == 'GET':
        if session:
            return redirect(url_for("func.index"))
        else:
            return render_template("Login_new.html")
            # return render_template("Login.html")
    else:
        data = request.get_json()
        email = data['email']
        password = data['password']
        online = data['online']
        user = UserModel.query.filter_by(email=email).first()
        if not user:
            return jsonify({
                'success': False,
                'message': '用户不存在'
            })
        if check_password_hash(user.password, password):
            session['user_id'] = user.id
            return jsonify({
                'success': True,
                'message': '登录成功'
            })
            # return redirect(url_for("func.index"))
        else:
            return jsonify({
                'success': False,
                'message': '密码错误'
            })

@bp.route("/register", methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template("Register_new.html")
    else:
        # 对用户提交的注册表单进行后端验证
        data = request.get_json()
        email = data['email']
        captcha = data['captcha']
        formValidate = True
        # 1、邮箱是否已被注册
        user = UserModel.query.filter_by(email=email).first()
        if user:
            formValidate = False
            return jsonify({
                'success': formValidate,
                'message': '该邮箱已被注册'
            })
        # 2、验证码是否正确
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            formValidate = False
            return jsonify({
                'success': formValidate,
                'message': '验证码填写错误'
            })
        else:
            db.session.delete(captcha_model)
            db.session.commit()

        if formValidate:
            email = data['email']
            username = data['username']
            password = data['password']
            user = UserModel(email=email,username=username,password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()

            nowuser = UserModel.query.filter_by(email=email).first()

            #在创建用户时自动添加三个示例树种
            Eglobulus = SpeciesModel(
                speciesname='E.globulus',
                user_id=nowuser.id,
            )

            Pradiata = SpeciesModel(
                speciesname='P.radiata',
                user_id=nowuser.id,

                pFS2=0.8,
                pFS20=0.4,
                aS=0.0243,
                nS=2.72,
                pRx=0.6,
                pRn=0.25,

                gammaFx=0.03,
                gammaF0=0.001,
                tgammaF=36,
                gammaR=0.015,

                Tmin=0,
                Topt=20,
                Tmax=32,

                kF=1,

                SWconst=0.7,
                SWpower=9,

                fCalpha700=1.4,
                fCg700=0.7,

                m0=0,
                fN0=0.6,
                fNn=0,

                MaxAge=50,
                nAge=4,
                rAge=0.5,

                gammaNx=0,
                gammaN0=0,
                tgammaN=0,
                ngammaN=1,
                wSx1000=160,
                thinPower=1.5,
                mF=0,
                mR=0.2,
                mS=0.2,

                SLA0=5,
                SLA1=5,
                tSLA=2,

                k=0.5,
                fullCanAge=3,
                MaxIntcptn=0.15,
                LAImaxIntcptn=5,

                alpha=0.05,
                Y=0.47,

                MinCond=0,
                MaxCond=0.02,
                LAIgcx=3.33,
                CoeffCond=0.05,
                BLcond=0.2,

                fracBB0=0.5,
                fracBB1=0.1,
                tBB=5,

                rhoMin=0.48,
                rhoMax=0.48,
                tRho=4,

                aH=0,
                nHB=0,
                nHN=0,

                aV=0,
                nVB=0,
                nVN=0,

                Qa=-90,
                Qb=0.8,
                gDM_mol=24,
                molPAR_MJ=2.3
            )

            Trial = SpeciesModel(
                speciesname='Trial',
                user_id=nowuser.id,

                pFS2=1,
                pFS20=0.15,
                aS=0.095,
                nS=2.4,
                pRx=0.8,
                pRn=0.25,

                gammaFx=0.03,
                gammaF0=0.001,
                tgammaF=12,
                gammaR=0.015,

                Tmin=-999,
                Topt=16,
                Tmax=999,

                kF=1,

                SWconst=0.7,
                SWpower=9,

                fCalpha700=1.4,
                fCg700=0.7,

                m0=0,
                fN0=1,
                fNn=0,

                MaxAge=50,
                nAge=4,
                rAge=0.95,

                gammaNx=0,
                gammaN0=0,
                tgammaN=0,
                ngammaN=1,
                wSx1000=300,
                thinPower=1.5,
                mF=0,
                mR=0.2,
                mS=0.2,

                SLA0=6,
                SLA1=6,
                tSLA=2.5,

                k=0.5,
                fullCanAge=0,
                MaxIntcptn=0.15,
                LAImaxIntcptn=0,

                alpha=0.055,
                Y=0.47,

                MinCond=0,
                MaxCond=0.02,
                LAIgcx=3.33,
                CoeffCond=0.05,
                BLcond=0.2,

                fracBB0=0.15,
                fracBB1=0.15,
                tBB=1.5,

                rhoMin=0.5,
                rhoMax=0.5,
                tRho=4,

                aH=0,
                nHB=0,
                nHN=0,

                aV=0,
                nVB=0,
                nVN=0,

                Qa=-90,
                Qb=0.8,
                gDM_mol=24,
                molPAR_MJ=2.3
            )

            db.session.add_all([Eglobulus,Pradiata,Trial])
            db.session.commit()

            # 在创建用户时自动添加三个示例站点
            Forcett = SiteModel(
                sitename='Forcett',
                user_id=nowuser.id,
            )

            SEQld = SiteModel(
                sitename='SE Qld',
                user_id=nowuser.id,

                tmax1=30.12,
                tmax2=29.71,
                tmax3=28.33,
                tmax4=26.49,
                tmax5=24.11,
                tmax6=21.88,
                tmax7=21.25,
                tmax8=22.51,
                tmax9=25.25,
                tmax10=27.3,
                tmax11=28.83,
                tmax12=29.72,

                tmin1=19.37,
                tmin2=19.52,
                tmin3=17.52,
                tmin4=15.35,
                tmin5=13.19,
                tmin6=8.62,
                tmin7=7.23,
                tmin8=7.12,
                tmin9=9.95,
                tmin10=13.9,
                tmin11=16.92,
                tmin12=18.33,

                precip1=113.78,
                precip2=180.32,
                precip3=174.72,
                precip4=136.83,
                precip5=119.75,
                precip6=63.72,
                precip7=64.52,
                precip8=50.16,
                precip9=32.7,
                precip10=68.33,
                precip11=94.81,
                precip12=136.56,

                evap1=5.99,
                evap2=4.71,
                evap3=4.65,
                evap4=3.7,
                evap5=2.79,
                evap6=2.4,
                evap7=2.48,
                evap8=3.31,
                evap9=4.3,
                evap10=5.27,
                evap11=5.6,
                evap12=6.41,

                ra1=22.56,
                ra2=20.17,
                ra3=18.97,
                ra4=15.54,
                ra5=12.63,
                ra6=12.43,
                ra7=13.26,
                ra8=16.47,
                ra9=20.14,
                ra10=21.67,
                ra11=22.86,
                ra12=22.76,

                raind1=0,
                raind2=0,
                raind3=0,
                raind4=0,
                raind5=0,
                raind6=0,
                raind7=0,
                raind8=0,
                raind9=0,
                raind10=0,
                raind11=0,
                raind12=0,

                frost1=0,
                frost2=0,
                frost3=0,
                frost4=0,
                frost5=0,
                frost6=0,
                frost7=0,
                frost8=0,
                frost9=0,
                frost10=0,
                frost11=0,
                frost12=0
            )

            ESP1 = SiteModel(
                sitename='ESP1',
                user_id=nowuser.id,

                tmax1=20.79,
                tmax2=20.95,
                tmax3=19.16,
                tmax4=16.79,
                tmax5=13.66,
                tmax6=11.81,
                tmax7=11.46,
                tmax8=12.4,
                tmax9=14.09,
                tmax10=16.03,
                tmax11=17.08,
                tmax12=18.76,

                tmin1=7.8792,
                tmin2=8.4688,
                tmin3=7.2368,
                tmin4=5.9608,
                tmin5=4.1744,
                tmin6=2.4936,
                tmin7=2.1152,
                tmin8=2.432,
                tmin9=3.5056,
                tmin10=4.4648,
                tmin11=5.8112,
                tmin12=6.9112,

                precip1=60.17,
                precip2=58.48,
                precip3=64.94,
                precip4=89.33,
                precip5=98.49,
                precip6=104.36,
                precip7=103.79,
                precip8=101.64,
                precip9=95.09,
                precip10=102.93,
                precip11=88.64,
                precip12=84.04,

                evap1=4.21,
                evap2=4.17,
                evap3=2.95,
                evap4=1.78,
                evap5=1.23,
                evap6=0.75,
                evap7=0.84,
                evap8=1.24,
                evap9=1.84,
                evap10=2.53,
                evap11=3.25,
                evap12=3.85,

                ra1=23.1,
                ra2=19.76,
                ra3=13.83,
                ra4=8.98,
                ra5=5.9,
                ra6=4.12,
                ra7=4.9,
                ra8=7.74,
                ra9=11.69,
                ra10=16.39,
                ra11=19.82,
                ra12=21.92,

                raind1=12.73,
                raind2=10.8,
                raind3=14.01,
                raind4=16.59,
                raind5=18.46,
                raind6=16.58,
                raind7=19.77,
                raind8=19.67,
                raind9=19,
                raind10=18.15,
                raind11=17.01,
                raind12=15.93,

                frost1=0,
                frost2=0,
                frost3=0,
                frost4=0,
                frost5=0,
                frost6=0,
                frost7=0,
                frost8=0,
                frost9=0,
                frost10=0,
                frost11=0,
                frost12=0
            )

            db.session.add_all([Forcett,SEQld,ESP1])
            db.session.commit()

            return jsonify({
                'success': formValidate,
                'message': '注册成功，即将前往登录'
            })
        else:
            return redirect(url_for("auth.register"))

#bp.route:如果没有指定参数，默认就是get请求
#get是从服务器拿去数据，post是提交数据
@bp.route("/captcha/email")
def get_email_captcha():
    #/captcha/email?email=xxx
    email = request.args.get("email")
    #4/6数字和字母的组合
    sourse = string.digits * 4
    captcha = random.sample(sourse, 4)
    captcha = "".join(captcha)
    message = Message(subject="注册验证码", recipients=[email], body=f"您的验证码是:{captcha}")
    mail.send(message)
    #用数据库的方式存储
    email_captcha = EmailCaptchaModel(email=email,captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    # RESTful API
    # {code: 200/400/500, message:"", data:{}}
    return jsonify({"success":True, "message":"", "data":None})

@bp.route("/mail/test")
def mail_test():
    message = Message(subject="邮箱测试", recipients=["1119277174@qq.com"], body="这是一条测试邮件")
    mail.send(message)
    return "邮件发送成功"

@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("auth.login"))